package com.itkun.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.itkun.controller.utils.R;
import com.itkun.damain.Book;
import com.itkun.service.IBookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.util.List;
@CrossOrigin
@RestController
@RequestMapping("/books")
public class BookController2 {

    @Autowired
    private IBookService bookService;

    @GetMapping
    public R getAll(){
        //return bookService.list();
        //List<Book> bookList = bookService.list(true,bookList);
        return new R(true,bookService.list());
    }

    @PostMapping
    public R save(@RequestBody Book book) throws IOException {
        //return bookService.save(book);
        //Boolean flag = bookService.save(book);
        if (book.getUname().equals("000")) throw  new IOException();
        Boolean flag = bookService.save(book);
        return new R(flag,flag ? "添加成功^_^":"添加失败-_-!!!");
    }

    @PutMapping
    public R update(@RequestBody Book book){
        //return bookService.updateById(book);
        //Boolean flag = bookService.updateById(book);
        return new R(bookService.updateById(book));
    }

    @DeleteMapping("{id}")
    public R delete(@PathVariable  Integer id){
        //return bookService.removeById(id);
        //Boolean flag = bookService.removeById(id);
        return new R(bookService.removeById(id));
    }

    @GetMapping("{id}")
    public R getById(@PathVariable Integer id){
        //return bookService.getById(id);
        //Book book = bookService.getById(id);
        return new R(true,bookService.getById(id));
    }

    @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable  int currentPage,@PathVariable int pageSize, Book book){
        //return bookService.getPage(currentPage,pageSize);
        IPage<Book> page = bookService.getPage( currentPage, pageSize,book );
        //如果当前页码大于总页码，呢么执行查询操作，是当前页码等于总页码
        if (currentPage > page.getPages()){
            page = bookService.getPage((int)page.getPages(), pageSize,book);
        }
        return new R(true,page);
    }

}

